package model.tree
{
	
	import event.TripManagerEvent;
	
	import mx.collections.ArrayCollection;
	
	import valueObjects.VOPlace;
	import valueObjects.VOTrip;

	[Bindable]
	public class TripNode
	{
		
		
		// the trip data
		private var _tripData:VOTrip;
		
		
		[Embed("data/images/icons/icon1.png")]
		public static var ICON1:Class;
		
		public var icon:Class;
		public var label:String;
		public var children:ArrayCollection;

		
		

		
		
		
		/*********************************
		 *    Attributes
		 ********************************/
		public function get tripData():VOTrip
		{
			return _tripData;
		}

		/**
		 * @private
		 */
		public function set tripData(value:VOTrip):void
		{
			_tripData = value;
			
			// refreshing all of the childrens
			// init the Trip object
			children.removeAll();
			
			for each (var place:VOPlace in _tripData.places_list)
			{
				trace(place.name + "," + place.place_id + "," + place.user_description);
				children.addItem(new PlaceNode(place));
			}
			
		}
		
		/**
		 *  Adds a new trip to the trip data, and also refreshes it's representation
		 * @param trip: the new trip
		 */ 
		public function addPlace(place:PlaceNode):void
		{
			// adding as the representation
			children.addItem(place);
			
			// syncronize with the database			
			updateTrip();
		}
		
		public function updateTrip():void
		{
			// update the children of the trip
			var newPlaces:ArrayCollection = new ArrayCollection();
			for each (var place:PlaceNode in children)
				newPlaces.addItem(place.placeData);
				
			_tripData.places_list = newPlaces;
			
			// automaticaly send the data to the server
			var tripEvent:TripManagerEvent = new TripManagerEvent(TripManagerEvent.SAVE_TRIP);
			tripEvent.additionalData.trip = _tripData;
			tripEvent.dispatch();
		}

		public function TripNode(trip:VOTrip):void
		{

			//_name = trip.name;
			
			//_tripId = parseInt( trip.trip_id );
			//_state = parseInt( trip.state );

			// save the trip Data into the local storage
			_tripData = trip;
			// if it's a new trip then it must be updatet in order to get a new id
			if (_tripData.trip_id == "-1")
				updateTrip();
			
			// set visual properties
			label = tripData.name;
			icon = ICON1;
			
			// init the Trip object
			children = new ArrayCollection();
			
			for each (var place:VOPlace in trip.places_list)
			{
				trace(place.name + "," + place.place_id + "," + place.user_description);
				children.addItem(new PlaceNode(place));
			}
		}
		

	}
}